package com.general.framework.controller;

import cn.dev33.satoken.stp.StpUtil;
import com.general.framework.common.Result;
import com.general.framework.entity.User;
import com.general.framework.service.MenuService;
import com.general.framework.service.UserService;
import com.general.framework.service.UserRoleService;
import com.general.framework.util.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/auth")
public class AuthController {
    @Autowired
    private UserService userService;

    @Autowired
    private MenuService menuService;

    @Autowired
    private UserRoleService userRoleService;

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    @Autowired
    private RedisUtil redisUtil;

    @Value("${sa-token.timeout}")
    private long timeout;

    private final BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();

    @PostMapping("/login")
    public Result login(@RequestBody User user) {
        // 根据用户名查找用户
        User dbUser = userService.findByUsername(user.getUsername());
        if (dbUser == null) {
            return Result.error("用户名或密码错误");
        }

        // 验证密码
        if (user.getPassword() == null) {
            return Result.error("密码不能为空");
        }
        if (!passwordEncoder.matches(user.getPassword(), dbUser.getPassword())) {
            return Result.error("用户名或密码错误");
        }

        // 登录成功，生成 Token
        StpUtil.login(dbUser.getId());
        String token = StpUtil.getTokenValue();
        
        // 获取权限信息
        List<String> permissions = menuService.getPermissionsByUserId(dbUser.getId());
        List<String> roles = userRoleService.getRolesByUserId(dbUser.getId());

        // 如果需要存储额外的用户信息，可以使用Sa-Token的Session
        StpUtil.getSession().set("permissions", permissions);
        StpUtil.getSession().set("roles", roles);

        return Result.success()
            .put("token", token)
            .put("user", dbUser)
            .put("permissions", permissions)
            .put("roles", roles);
    }

    @GetMapping("/logout")
    public Result logout() {
        try {
            // Sa-Token的logout会自动清理相关的Redis数据
            StpUtil.logout();
            return Result.success("退出成功");
        } catch (Exception e) {
            return Result.error("退出失败：" + e.getMessage());
        }
    }
}